﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Mail;
using Ctef.Web.Extensions;
using Ctef.Web.Interfaces;
using Ctef.Web.Models;

namespace Ctef.Web.Repositories
{
    public class EmailRepository : IEmailRepository
    {
        private string VolunteerRecipientKey = "VolunteerRegistrationRecipients";
        private string PledgeRecipientKey = "PledgeRegistrationRecipients";

        public bool SendEmail(VolunteerInfoViewModel model)
        {
            if (!model.IsValid())
            {
                return false;
            }

            return SendEmail(
                model.ComposeEmailSubject(),
                model.ComposeEmailBody(),
                GetRecipients(VolunteerRecipientKey));
        }

        public bool SendEmail(PledgeViewModel model)
        {
            if (!model.IsValid())
            {
                return false;
            }

            return SendEmail(
                model.ComposeEmailSubject(), 
                model.ComposeEmailBody(), 
                GetRecipients(PledgeRecipientKey));
        }

        private static bool SendEmail(string subject, string body, IEnumerable<string> recipients)
        {
            bool emailSent = false;
            if (string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(body) || recipients.IsNullOrEmpty())
            {
                return emailSent;
            }
            
            try
            {
                var message = new MailMessage();
                var smtp = new SmtpClient
                {
                    Host = "relay-hosting.secureserver.net"
                };

                message.From = new MailAddress("china.tomorrow@ctef.org", "China Tomorrow Education Foundation");

                foreach (var r in recipients)
                {
                    message.To.Add(new MailAddress(r.Trim()));
                }

                message.IsBodyHtml = false;
                message.Subject = subject;
                message.Body = body;

                smtp.Send(message);
                emailSent = true;
            }
            catch (Exception)
            {
                // TODO: log exception 
            }

            return emailSent;
        }

        private static IEnumerable<string> GetRecipients(string key)
        {
            var recipients = ConfigurationManager.AppSettings[key];

            return !recipients.IsNullOrWhiteSpace() ?
                recipients.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries) : null;
        }
    }
}